from zoneinfo import ZoneInfo
from flask import request
from datetime import datetime, timezone
from flaskapp.entity.Book import Book
from flaskapp.entity.Record import Record
from flaskapp.exts import db
from flaskapp.entity.User import User
from flaskapp.entity.Consultation import Consultation
from flaskapp.util.Jwt import generate_token
from flaskapp.util.Redprint import Redprint
from flaskapp.util.Result import Result

api = Redprint('users')


# 注册
@api.route('/register', methods=['POST'])
def register():
    data = request.json
    username = data['username']
    password = data['password']
    category = 'student'
    is_admin = False
    new_user = User(username, password, category, is_admin)
    new_user.addUser()
    return Result.success(new_user.to_dict(), 'register success')


@api.route('/login', methods=['POST'])
def login_confirm():
    data = request.json
    if 'username' not in data or 'password' not in data:
        return Result.error(400, "Username and password are required")
    username = data['username']
    password = data['password']
    user = User.query.filter_by(username=username).first()
    print(user.is_admin)
    if user and user.password == password:
        if user.is_admin == 1:
            token = generate_token(user.userid, True)
            user.token = token
            db.session.commit()
            data = {
                'userid': user.userid,
                'token': token,
                'is_admin': user.is_admin
            }
            return Result.success(data, "Login successful and you are the admin")
        else:
            token = generate_token(user.userid, False)
            user.token = token
            db.session.commit()
            data = {
                'userid': user.userid,
                'token': token,
                'is_admin': user.is_admin
            }
            return Result.success(data, "Login successful and you are not the admin")
    else:
        return Result.error(401, "Invalid username or password")


# 检查用户是否存在
@api.route('/isExist', methods=['POST'])
def isExist():
    data = request.json
    username = data['username']
    user = User.query.filter_by(username=username).first()
    if user is None:
        return Result.error(404, "User not found")
    else:
        return Result.success(True, "User exist")


# 创建咨询
@api.route('/createConsultation', methods=['POST'])
def createConsultation():
    data = request.json
    from_whom = data['from_whom']
    content = data['content']
    # 获取当前的UTC时间
    utc_now = datetime.now(timezone.utc)

    # 将UTC时间转换为东八区时间（UTC+8）
    cst_timezone = ZoneInfo("Asia/Shanghai")  # 使用Asia/Shanghai作为东八区的时区标识
    cst_now = utc_now.astimezone(cst_timezone)
    consultation = Consultation(from_whom, content, cst_now)
    return Result.success(consultation.to_dict(), "Consultation created successfully")


# 获取某用户已借阅的书籍
@api.route('/getBorrowedBooks/<userid>', methods=['GET'])
def getBorrowedBooks(userid):
    user = User.query.filter_by(userid=userid).first()
    records = Record.query.filter_by(userid=userid).all()
    borrowedBooks = []
    if user is None:
        return Result.error(404, "User not found")
    if records is not None:
        for record in records:
            book = Book.query.filter_by(bookid=record.bookid).first()
            data = {
                'recordid': record.recordid,
                'bookid': book.bookid,
                'bookname': book.bookname,
                'author': book.author,
                'press': book.press,
                'surplus': book.surplus,
                'category': book.category,
                'expire_time': record.getExpireTime()
            }
            borrowedBooks.append(data)
        return Result.success(borrowedBooks)
    else:
        return Result.error(404, "no borrowed book")
